<html lang="">

<head>
    <meta charset="UTF-8">
    <title>Simple Recorder.js demo with record, stop and pause</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
<div id="controls">
    <button id="recordButton">Record</button>
    <button id="stopButton">Stop</button>
    <button id="playButton">playButton</button>
</div>

</body>
<script type="text/javascript" src="./js/recorder.js"></script>
<script>

    let recorder = new Recorder({
        sampleBits: 16,                 // 采样位数，支持 8 或 16，默认是16
        sampleRate: 16000,              // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1,                 // 声道，支持 1 或 2， 默认是1
        compiling: true,
        // (0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
    });

    var recordButton = document.getElementById("recordButton");
    var stopButton = document.getElementById("stopButton");
    var playButton = document.getElementById("playButton");

    recordButton.addEventListener("click", startRecording);
    stopButton.addEventListener("click", stopRecording);
    playButton.addEventListener("click", playRecording);

    //实现WebSocket
    var ws = null;
    //定义一个定时器
    var timeInte = null;


    // 录音
    function startRecording() {
        console.log("recordButton clicked");
        recorder.start().then(() => {
            // 开始录音
        }, (error) => {
            // 出错了
            console.log(`出错了`);
        });
        useWebSocket();
    }

    // 停止录音
    function stopRecording() {
        console.log("stopButton clicked", recorder.getPCMBlob());
        recorder.getPCMBlob();
        recorder.downloadPCM('aaa');
    }

    // 播放录音
    function playRecording() {
        recorder.play();
    }

    // 推荐使用
    recorder.onprogress = function (params) {
        console.log('录音时长', params.duration);
        console.log('已录音文件大小（字节）', params.fileSize);
        console.log('录音音量百分比', params.vol);
        var data = params.data;
        console.log('当前录音的总数据', data);

        console.log('readyState' + ws.readyState);
        //ws进入连接状态，则每隔500毫秒发送一包数据
        if (ws.readyState === 1) {

            console.log("getWholeData" + data)

            var r = this.flat();
            r = recorder.compress(r, this.inputSampleRate, this.outputSampleRate), this.data = t.encodePCM(r, this.oututSampleBits, this.littleEdian)
            new Blob([r])
            console.log(" new Blob([r])" + new Blob([r]))
            // ws.send(params.data.getPCM());
        }

    };

    /*    function createDownloadLink(blob) {
            console.log(blob);
            var filename = new Date().toISOString();
            downloadBlob(blob, filename)
        }
        function downloadBlob(content, fileName) {
            const blob = new Blob([content]);
            const a = document.createElement("a");
            const url = window.URL.createObjectURL(blob);
            const filename = fileName + '.pcm';
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
        }*/
    /*

    * WebSocket

    */

    function useWebSocket() {

        ws = new WebSocket("ws://" + window.location.host + "/websocket/chat/audio");

        //传输的是 ArrayBuffer 类型的数据
        ws.binaryType = 'arraybuffer';

        ws.onopen = function () {

            console.log('握手成功');
            console.log("readyState" + ws.readyState);
            if (ws.readyState === 1) { //ws进入连接状态，则每隔500毫秒发送一包数据

                // recorder.start().then(() => {
                //     // 开始录音
                // }, (error) => {
                //     // 出错了
                //     console.log(`出错了`);
                // });
                console.log('握手成功');
            }

        };

        timeInte = setInterval(function () {
            console.log('readyState' + ws.readyState);
            //ws进入连接状态，则每隔500毫秒发送一包数据
            if (ws.readyState === 1) {

                // console.log(recorder.getPCMBlob());
                //发送音频数据
                // ws.send(recorder.getPCMBlob());

            }
        }, 500);  //每隔500ms发送一次，定时器


        ws.onmessage = function (msg) {

            console.info(msg)

        };


        ws.onerror = function (err) {

            console.info(err)

        }

    }

</script>


</html>
